package com.panlin.daohang

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class PermissionUtils private constructor(private val context: Context) {

    companion object {
        private var instance: PermissionUtils? = null
        private const val PERMISSION_REQUEST_CODE = 100
        private const val LOCATION_SETTINGS_REQUEST_CODE = 200

        @Synchronized
        fun getInstance(context: Context): PermissionUtils {
            if (instance == null) {
                instance = PermissionUtils(context.applicationContext)
            }
            return instance!!
        }
    }

    // 权限回调接口
    interface PermissionCallback {
        fun onGranted() // 权限已授予
        fun onDenied(deniedPermissions: List<String>) // 权限被拒绝
        fun onPermanentlyDenied(permanentlyDeniedPermissions: List<String>) // 权限被永久拒绝
    }

    // 检查并申请位置权限
    fun checkAndRequestLocationPermission(activity: Activity, callback: PermissionCallback) {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                Manifest.permission.FOREGROUND_SERVICE_LOCATION
            )
        } else {
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.FOREGROUND_SERVICE_LOCATION
            )
        }

        // 先显示权限说明
        if(!hasPermissions(permissions)){
            showPermissionRationale(activity) {
                requestPermissions(activity, permissions, callback)
            }
        }
    }

    // 检查单个权限
    private fun hasPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) ==
                PackageManager.PERMISSION_GRANTED
    }

    // 检查多个权限
    private fun hasPermissions(permissions: Array<String>): Boolean {
        return permissions.all { hasPermission(it) }
    }

    // 显示权限说明对话框
    private fun showPermissionRationale(activity: Activity, onConfirm: () -> Unit) {
        AlertDialog.Builder(activity)
            .setTitle("需要定位权限")
            .setMessage("为了给您提供更好的服务,我们需要获取定位权限。\n\n" +
                    "我们承诺:\n" +
                    "1. 只在必要时获取位置信息\n" +
                    "2. 不会泄露您的位置信息\n" +
                    "3. 您可以随时在设置中关闭定位权限")
            .setPositiveButton("确定") { _, _ -> onConfirm() }
            .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
            .show()
    }

    // 申请权限
    private fun requestPermissions(
        activity: Activity,
        permissions: Array<String>,
        callback: PermissionCallback
    ) {
        // 检查哪些权限需要申请
        val permissionsToRequest = permissions.filter {
            ContextCompat.checkSelfPermission(context, it) !=
                    PackageManager.PERMISSION_GRANTED
        }

        when {
            permissionsToRequest.isEmpty() -> {
                // 已有所有权限
                callback.onGranted()
            }
            permissionsToRequest.any {
                ActivityCompat.shouldShowRequestPermissionRationale(activity, it)
            } -> {
                // 部分权限被拒绝过,需要解释
                showPermissionSettings(activity, permissionsToRequest, callback)
            }
            else -> {
                // 申请权限
                ActivityCompat.requestPermissions(
                    activity,
                    permissionsToRequest.toTypedArray(),
                    PERMISSION_REQUEST_CODE
                )
            }
        }
    }

    // 显示权限设置引导
    private fun showPermissionSettings(
        activity: Activity,
        permissions: List<String>,
        callback: PermissionCallback
    ) {
        AlertDialog.Builder(activity)
            .setTitle("需要权限")
            .setMessage("这些权限对于应用的正常运行是必需的,请在设置中开启。")
            .setPositiveButton("去设置") { _, _ ->
                // 跳转到应用设置界面
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.fromParts("package", activity.packageName, null)
                }
                activity.startActivityForResult(intent, PERMISSION_REQUEST_CODE)
            }
            .setNegativeButton("取消") { _, _ ->
                callback.onPermanentlyDenied(permissions)
            }
            .show()
    }

    // 检查位置服务是否开启
    fun checkLocationService(activity: Activity, callback: () -> Unit) {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
            !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

            // 提示开启位置服务
            AlertDialog.Builder(activity)
                .setTitle("开启定位服务")
                .setMessage("请开启手机的定位服务以获取位置信息")
                .setPositiveButton("去设置") { _, _ ->
                    // 跳转到位置服务设置界面
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    activity.startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE)
                }
                .setNegativeButton("取消", null)
                .show()
        } else {
            callback()
        }
    }
}